<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="群聊名称" prop="title">
        <el-input
          v-model="queryParams.chatName"
          placeholder="请输入群聊名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="群聊类型" prop="chatType">
        <el-input
          v-model="queryParams.chatType"
          placeholder="请输入群聊类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['business:dingTalk:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:dingTalk:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:dingTalk:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['business:dingTalk:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          @click="handleRefreshCache"
          v-hasPermi="['business:dingTalk:refreshCache']"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div ref="divTable" :style="'height:' + divHeight + 'px'">
      <el-table v-loading="loading" :data="dingTalkList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="50">
          <template v-slot="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="群聊名称" align="center" prop="chatName" />
        <el-table-column label="群聊类型" align="center" prop="chatType" >
          <template v-slot="scope">
            <el-tag v-if="scope.row.chatType === 'DR'" type="success">异常退回</el-tag>
            <el-tag v-if="scope.row.chatType === 'REFUND'" type="success">在途退款</el-tag>
            <el-tag v-if="scope.row.chatType === 'DUH'" type="success">3C待优化</el-tag>
            <el-tag v-if="scope.row.chatType === 'DBH'" type="success">海报待优化</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Webhook" align="center" prop="webhook" show-overflow-tooltip/>
        <el-table-column label="加签" align="center" prop="secret" show-overflow-tooltip/>
        <el-table-column label="追加@人" align="center" prop="atMobiles" >
          <template v-slot="scope">
            <user-tag :value="scope.row.atMobiles" type="phoneNumber"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="dingStatus" >
          <template v-slot="scope">
            <dict-tag :options="dict.type.sys_status" :value="scope.row.dingStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:dingTalk:edit']"
            >修改</el-button>
            <el-button
              type="text"
              :icon="scope.row.dingStatus === 'DELETED' ? 'el-icon-refresh-left' : 'el-icon-delete'"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['business:dingTalk:remove']"
            >{{scope.row.dingStatus === 'DELETED' ? "恢复" : "删除" }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :pageRefs="this.$refs"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </div>
    <!-- 添加或修改钉钉配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="群聊名称" prop="chatName">
          <el-input v-model="form.chatName" clearable placeholder="请输入群聊名称" />
        </el-form-item>
        <el-form-item label="群聊类型" prop="chatType">
          <el-radio-group v-model="form.chatType">
            <el-radio-button label="DR">异常退回</el-radio-button>
            <el-radio-button label="REFUND">在途退款</el-radio-button>
            <el-radio-button label="DUH">3C待优化</el-radio-button>
            <el-radio-button label="DBH">海报待优化</el-radio-button>
            <el-radio-button label="RPA">自动处理</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="Webhook" prop="webhook">
          <el-input v-model="form.webhook" clearable placeholder="请输入钉钉机器人webhook" />
        </el-form-item>
        <el-form-item label="加签" prop="secret">
          <el-input v-model="form.secret" clearable placeholder="请输入钉钉机器人加签" />
        </el-form-item>
        <el-form-item prop="atMobiles">
          <span slot="label">
            <el-tooltip content="追加@的人，默认根据规则@人；若填写此字段，则为追加@人" placement="top">
            <i class="el-icon-question"></i>
            </el-tooltip>
            追加@人
          </span>
          <el-select v-model="form.atMobiles" clearable filterable multiple placeholder="请选择追加@人" style="width: 100%">
            <el-option
              v-for="item in userOptions"
              :key="item.userName"
              :label="item.nickName"
              :value="item.userName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" clearable type="textarea" :rows="2" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listDingTalk, getDingTalk, delDingTalk, addDingTalk, updateDingTalk, exportExcel, refreshCache } from "@/api/business/dingTalk";
import { getNormalUserInfo} from "@/api/system/user";
import ResizeMixin from "@/layout/mixin/ResizeHandler";

export default {
  name: "DingTalk",
  mixins: [ResizeMixin],
  dicts: ['sys_status'],
  data() {
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 钉钉配置表格数据
      dingTalkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chatName: null,
        chatType: null,
        webhook: null,
        secret: null,
        atMobiles: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        chatName: [
          { required: true, message: "群聊名称不能为空", trigger: "blur" }
        ],
        chatType: [
          { required: true, message: "群聊类型不能为空", trigger: "blur" }
        ],
        webhook: [
          { required: true, message: "Webhook不能为空", trigger: "blur" }
        ],
        secret: [
          { required: true, message: "加签不能为空", trigger: "blur" }
        ],
      },
      // 用户选项
      userOptions: [],
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 查询钉钉配置列表 */
    getList() {
      this.loading = true;
      listDingTalk(this.queryParams).then(response => {
        this.dingTalkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        chatName: null,
        chatType: null,
        webhook: null,
        secret: null,
        atNickNames: null,
        atMobiles: null,
        remark: null
      };
      this.$resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加钉钉配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDingTalk(id).then(response => {
        this.form = response.data;
        // 将atMobiles转为数组
        this.form.atMobiles = this.form.atMobiles ? this.form.atMobiles.split(",") : [];
        this.open = true;
        this.title = "修改钉钉配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.atMobiles) {
        this.form.atMobiles = this.form.atMobiles.join(",");
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDingTalk(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDingTalk(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('注意：此删除不可恢复，是否确认删除？').then(function() {
        return delDingTalk(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportExcel(this.queryParams)
    },
    /** 删除或恢复按钮操作 */
    handleChangeStatus(row) {
      let status = row.dingStatus === 'NORMAL'? '删除' : '恢复';
      this.$modal.confirm('是否确认' + status + '此数据项？').then(function() {
        row.dingStatus = row.dingStatus === 'NORMAL'? 'DELETED' : 'NORMAL';
        return updateDingTalk({ id: row.id, dingStatus: row.dingStatus })
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(status + "成功");
      }).catch(() => {});
    },
    /** 刷新缓存 */
    handleRefreshCache(){
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    },
    /** 获取用户集合 */
    getUserList(){
      getNormalUserInfo().then(response => {
        this.userOptions = response.data;
      });
    },
  }
};
</script>
